package com.atguigu.guli.service.oss.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.guli.service.oss.config.OssConfig;
import com.atguigu.guli.service.result.R;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RequestMapping("/admin/oss/file")
//@CrossOrigin
@RestController
public class FileController {


    @Autowired
    OssConfig ossConfig;

    @PostConstruct
    public void get() {
        this.schen = ossConfig.getSchen();
        this.endpoint = ossConfig.getEndpoint();
        this.accessKeyId = ossConfig.getAccessKeyId();
        this.accessKeySecret = ossConfig.getAccessKeySecret();
        this.bucketName = ossConfig.getBucketName();
    }

    String schen;
    String endpoint;
    String accessKeyId;
    String accessKeySecret;
    //自己创建的捅名
    String bucketName;


    @PostMapping("/upload")
    public R upload(MultipartFile file, String model) {
        //获取文件名字
        String filename = file.getOriginalFilename();
        // 创建OSSClient实例。连接到阿里
        OSS ossClient = new OSSClientBuilder().build(schen + endpoint, accessKeyId, accessKeySecret);

        InputStream inputStream = null;
        try {
            //获取文件的输入流
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //创建多级目录
        String day = new DateTime().toString("/yyyy/MM-dd/");

        //拼接,创建上传文件的名字,要唯一  model是文件存储的文件夹
        String FileName = model + day + UUID.randomUUID().toString().replace("-", "").substring(0, 12) +
                filename.substring(filename.lastIndexOf("."));
// 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
        ossClient.putObject(bucketName, FileName, inputStream);

// 关闭OSSClient。
        ossClient.shutdown();

        //  https://sh210225-guli.oss-cn-shanghai.aliyuncs.com/active/2021/10-28b3405f3fbad0.png
        String url = schen + bucketName + "." + endpoint + "/" + FileName;

        return new R().data("url", url);

    }

    @DeleteMapping("/del")
    public R del(String path, String model) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        path = path.substring(path.lastIndexOf(model + "/"));

        ossClient.deleteObject(bucketName, path);

// 关闭OSSClient。
        ossClient.shutdown();

        return R.ok();
    }
}
